<%@ page contentType='text/html; charset=UTF-8'%>
 
<%@ taglib prefix='s' uri='/struts-tags'%>

<link rel='stylesheet' type='text/css' href='<s:url value="/plugins/jquery-ui-1.8.13/css/custom-theme/jquery-ui-1.8.13.custom.css" />' />
<link rel='stylesheet' type='text/css' href='<s:url value="/plugins/jqGrid-4.0.0/css/ui.jqgrid.css" />' />
<link rel='stylesheet' type='text/css' href='<s:url value="/plugins/jquery-autocomplete/jquery.autocomplete.css" />' />
<script type='text/javascript' src='<s:url value="/plugins/jquery-ui-1.8.13/js/jquery-ui-1.8.13.custom.min.js" />'></script>
<script type='text/javascript' src='<s:url value="/plugins/jqGrid-4.0.0/js/i18n/grid.locale-es.js" />'></script>
<script type='text/javascript' src='<s:url value="/plugins/jqGrid-4.0.0/js/jquery.jqGrid.min.js" />'></script>
<script type='text/javascript' src='<s:url value="/plugins/jquery-autocomplete/jquery.ajaxQueue.js" />'></script>
<script type='text/javascript' src='<s:url value="/plugins/jquery-autocomplete/jquery.autocomplete.js" />'></script>
<script type='text/javascript' src='<s:url value="/plugins/jquery-autocomplete/jquery.bgiframe.min.js" />'></script>
<script type='text/javascript' src='<s:url value="/plugins/jquery-autocomplete/jquery.thickbox-compressed.js" />'></script>

<p>
<input type='button' id='agregar' value='Agregar' />
<input type='button' id='editar' value='Editar' />
<input type='button' id='eliminar' value='Eliminar' />
<input type='button' id='buscar' value='Buscar' /></p>
<div id='i-gridContainer'>
    <table id='cursoGrid'><tr><td/></tr></table>
</div>
<div id='pager'></div>
<p><input id="ofertar" type="button" value="Ofertar curso" disabled="disabled" /></p>
<s:form name="formOfertar" action="ofertarCurso">
<input type="hidden" name="idcurso" />
<input type="hidden" name="diasoferta" />
</s:form>

<script type='text/javascript'>
var w = {
      currentRow: null
    },
    categoria = 'Idiomas:Idiomas;Capacitacion profesional:Capacitacion profesional',
    dias = 'Lunes-Miercoles 3_30pm-5_30pm:Lunes-Miercoles 3_30pm-5_30pm;Lunes-Miercoles 3pm-5pm:Lunes-Miercoles 3pm-5pm;Martes-Jueves 3_30pm-5_30pm:Martes-Jueves 3_30pm-5_30pm;Martes-Jueves 2_30pm-6_30pm:Martes-Jueves 2_30pm-6_30pm;Sabados 8_30am-12_30pm:Sabados 8_30am-12_30pm',
    buildSelect = function(options, elem, val){
        var $s = undefined === elem ? $('<select></select>') : $(elem);
        $s.empty();
        $.each(options.split(';'), function(){
            var opt = this.split(':');
            opt[0] = opt[0].replace(/_/g, ':');
            opt[1] = opt[1].replace(/_/g, ':');
            var selected = undefined !== val && opt[0] == val ? ' selected=\'selected\'' : '';
            $s.append('<option value=\'' + opt[0] + '\'' + selected + '>' + opt[1] + '</option>');
        });
        return $s;
    },
    htmlSelect = function(options){
        var $s = buildSelect(options);
        return '<select>' + $s.html() + '</select>';
    }
    formOptions = {
        addCaption: 'Agregar registro de curso',
        editCaption: 'Modificar registro de curso',
        modal: true,
        recreateForm: true,
        bSubmit: 'Guardar',
        bCancel: 'Cancelar',
        bClose: 'Cerrar',
        saveData: 'Se han modificado datos, desea guardar?',
        bYes: 'Sí',
        bNo: 'No',
        bExit: 'Cancelar',
        errorTextFormat: function(msg){
           msg = jQuery.parseJSON(msg.responseText);
           var r = '<ul class="jq-error-ul">';
           $.each(msg, function(key, val){
               r += '<li><b>' + key + '</b>:' + val + '</li>';
           })
           return r + '</ul>';
        }
    },
    formEditOptions = {},
    formCreateOptions = {};

$.extend(formEditOptions, formOptions, {
    url: '<s:url action="editarCurso" />',
    closeAfterEdit: true
});
$.extend(formCreateOptions, formOptions, {
    url: '<s:url action="crearCurso" />',
    closeAfterAdd: true
});

jQuery('#cursoGrid').jqGrid({  
    url:'<s:url action="listarCurso" />',
    datatype: 'json',  
    colNames:['Nombre', 'Costo', 'Categoría','Descripción','Horas de duración'],  
    colModel:[  
        {
            name: 'nombre',
            index: 'nombre',
            width:60,
            editable: true
        },
        {
            name:'costo',
            index:'costo',
            width:20,
            editable: true,
            sorttype: 'int',
            searchoptions: {
                sopt: ['eq','ne','lt','le','gt','ge']
            }
        },  
        {
            name:'categoria',
            index:'categoria',
            width:60,
            editable:true,
            edittype: 'select',
            editoptions: {
                value: categoria
            },
            stype: 'select',
            searchoptions: {
                dataUrl: '<s:url action="dummy" />',//No se va a usar, queremos que se llame a buildSelect
                buildSelect: function(){return htmlSelect(categoria)},
                dataInit: function(elem){
                    $(elem).change();
                },
                sopt: ['eq','ne']
            }
        },
        {
            name:'descripcion',
            index:'descripcion',
            width:150,
            editable: true
        },       
        {
            name: 'horas_dur',
            index: 'horas_dur',
            width: 20,
            editable: true,
            sorttype: 'int',
            searchoptions: {
                sopt: ['eq','ne','lt','le','gt','ge']
            }
        }
    ],
    rowNum:20,
    rowList:[10,20,50,100],
    pager: $('#pager'),
    viewrecords: true,
    sortorder: 'desc',
    caption: 'Curso',
    width:650,
    height: 'auto',
    onSelectRow: function(id){
        $('#editar,#eliminar,#ofertar').removeAttr('disabled');
        w.currentRow = id;
        $('input[name=idcurso]').val(id);
    },
    onPaging: function(){
        $('#editar,#eliminar,#ofertar').attr('disabled', true);
        w.currentRow = null;
    }
});
$('#editar').attr('disabled', true).click( function() {
    if (null == w.currentRow){
        return;
    }
    $('#cursoGrid').editGridRow(w.currentRow, formEditOptions);
});
$('#agregar').click( function() {
    $('#cursoGrid').editGridRow('new', formCreateOptions);
});
$('#buscar').click(function(){
    $('#cursoGrid').searchGrid({
        caption: 'Buscar...',
        Find: 'Encontrar',
        Reset: 'Resetear',
        odata : ['igual', 'no igual', 'menor', 'menor o igual','mayor','mayor o igual', 'comienza por','no comienza por','está en','no está en','termina en','no termina en','contiene','no contiene'],
        onInitializeSearch: function(){
            $('div.searchFilter select.opsel').html("<option value='AND'>Todas</option><option value='OR'>Alguna</option>");
        },
        closeAfterSearch: true,
        multipleSearch: true
    });
});
$('#ofertar').attr('disabled', true).click( function() {
    if (null == w.currentRow){
        return;
    }
    var user_input = prompt('Introduzca los dias:');
    //if (userInput != '' && userInput != null) {
        $('input[name=diasoferta]').val(user_input);
        document.formOfertar.submit();
    //}
});
$('#eliminar').attr('disabled', true).click( function() {
    if (null == w.currentRow){
        return;
    }
    $('#cursoGrid').delGridRow(w.currentRow, {
        url: '<s:url action="eliminarCurso" />',
        errorTextFormat: function(msg){
           msg = jQuery.parseJSON(msg.responseText);
           var r = '<ul class="jq-error-ul">';
           $.each(msg, function(key, val){
               r += '<li><b>' + key + '</b>:' + val + '</li>';
           })
           return r + '</ul>';
        }
    });
});
</script>